package com.java.dao.impl;

import com.java.dao.BaseAdminDao;
import com.java.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * @ClassName AdminDaoMysql
 * @Description BaseAdminDao实现类
 * @Author 0715-YuHao
 * @Date 2020/9/8 13:04
 */
public class AdminDaoMysql extends DruidUtil implements BaseAdminDao {
    /**
     * @Author 0715-YuHao
     * @Description 更新登录时间、登录IP、登录状态
     * @Date 23:46 2020/9/11
     **/
    private static final String SQL_UPDATE_LOGIN_TIME = "UPDATE eadmin SET logintime=?,loginIp=? WHERE username=?";

    /**
     * @Author 0715-YuHao
     * @Description 通过用户名与密码登录，并判断该用户是否登录
     * @Date 23:49 2020/9/11
     **/
    private static final String SQL_LOGIN = "SELECT id FROM eadmin WHERE username=? and password=?";

    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        Connection conn = null;
        PreparedStatement state = null;
        try {
            conn = getConnection();
            state = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            state.setDate(1, new java.sql.Date(date.getTime()));
            state.setString(2, ip);
            state.setString(3, username);
            state.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            close(conn, state, null);
        }
    }

    @Override
    public boolean login(String username, String password) {
        Connection conn = null;
        PreparedStatement state = null;
        ResultSet res = null;
        try {
            conn = getConnection();
            state = conn.prepareStatement(SQL_LOGIN);
            state.setString(1, username);
            state.setString(2, password);
            res = state.executeQuery();
            return res.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            close(conn, state, res);
        }
        return false;
    }
}
